package com.atgugu.flink.chapter11.function;

import com.atgugu.flink.bean.WaterSensor;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.functions.AggregateFunction;

/**
 * @Author lzc
 * @Date 2022/4/12 13:36
 */
public class Flink03_Function_Aggregate {
    public static void main(String[] args) {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        DataStreamSource<WaterSensor> stream = env.fromElements(
            new WaterSensor("sensor_1", 1000L, 10),
            new WaterSensor("sensor_1", 2000L, 20),
            new WaterSensor("sensor_2", 3000L, 30),
            new WaterSensor("sensor_1", 4000L, 40),
            new WaterSensor("sensor_1", 5000L, 50),
            new WaterSensor("sensor_2", 6000L, 60)
        );
        
        StreamTableEnvironment tEnv = StreamTableEnvironment.create(env);
        Table table = tEnv.fromDataStream(stream);
        tEnv.createTemporaryView("sensor", table);
        
        
        // 自定义一个函数: 可以把小写字母变成大写字母
        
        // 1. 在table api中使用自定义函数
        // 1.1. 内联用法
        /*table
            .groupBy($("id"))
            .select($("id"), call(MyAvg.class, $("vc")).as("vc_avg"))
            .execute()
            .print();*/
        
        
        // 1.2. 先注册再使用
        
        
        // 2. 在sql中使用
        tEnv.createTemporaryFunction("my_avg", MyAvg.class);
        
        tEnv.sqlQuery("select id, my_avg(vc) from sensor group by id").execute().print();
        
        
    }
    
    public static class Avg {
        public Integer sum = 0;
        public Long count = 0L;
    }
    
    public static class MyAvg extends AggregateFunction<Double, Avg> {
        
        //初始化一个累加器
        @Override
        public Avg createAccumulator() {
            return new Avg();
        }
        
        // 对传入的值进行累加
        // 参数1: 必须是累加器
        // 其他参数: 需要参与聚合的值
        public void accumulate(Avg acc, Integer vc) {
            acc.sum += vc;
            acc.count++;
        }
        
        
        // 获取最终的聚合的结果
        @Override
        public Double getValue(Avg acc) {
            return acc.sum * 1.0 / acc.count;
        }
        
        
    }
    
    
}
